﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Server.Framework.Processor
{
    /// <summary>
    /// Author: Leil
    /// Description: 消息处理管理类
    /// CreateTime: 2020/5/11 23:21:04
    /// </summary>
    class ProcessorManager
    {
        private static readonly Dictionary<int, IProcessor> processorDic = new Dictionary<int, IProcessor>();

        /// <summary>
        /// 初始化消息处理器
        /// </summary>
        public static void Init()
        {
            ReflectionInit();
        }

        /// <summary>
        /// 反射初始化消息处理器
        /// </summary>
        public static void ReflectionInit()
        {
            Type[] typeArr = Assembly.GetExecutingAssembly().GetTypes();
            for (int i = 0; i < typeArr.Length; i++)
            {
                Type type = typeArr[i];

                object[] attributes = type.GetCustomAttributes(true);
                object[] processorAttrs = attributes.Where(attribute => attribute is ProcessorAttr).ToArray();
                if (processorAttrs.Length > 0)
                {
                    ProcessorAttr processorAttr = processorAttrs.First() as ProcessorAttr;
                    object instance = Activator.CreateInstance(type);
                    IProcessor processor = instance as IProcessor;
                    if (processor != null)
                    {
                        processorDic.Add(processorAttr.MessageId, processor);
                    }
                }
            }
        }

        /// <summary>
        /// 注册消息处理器
        /// </summary>
        /// <param name="messageId">消息号</param>
        /// <param name="processor">消息处理器</param>
        public static void RegisterProcessor(int messageId, IProcessor processor)
        {
            if (processor != null)
            {
                processorDic.Add(messageId, processor);
            }
        }

        /// <summary>
        /// 通过消息号获取消息处理器
        /// </summary>
        /// <param name="messageId">消息号</param>
        /// <returns>消息处理器</returns>
        public static IProcessor GetProcessor(int messageId)
        {
            if (processorDic.ContainsKey(messageId))
            {
                return processorDic[messageId];
            }
            return null;
        }

    }
}
